package com.cc.moxingvoice.utils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.cc.moxingvoice.R;
import com.cc.moxingvoice.constant.Connection;
import com.cc.moxingvoice.constant.LocalPath;
import com.cc.moxingvoice.constant.MyUrl;
import com.cc.moxingvoice.response.CheckUpdateResponse;
import com.superc.cframework.network.HttpResponse;
import com.superc.cframework.utils.ToastUtil;

import java.util.HashMap;

import androidkun.com.versionupdatelibrary.entity.VersionUpdateConfig;

/**
 * 创建日期：2018/3/3 on 15:57
 * 描述：
 * 作者：郭士超
 * QQ：1169380200
 */

public class CheckUpdateUtil {

    /**
     * 检查更新
     */
    public static void checkUpdate(final Context context, final boolean showToast) {
        int versionCode = 0;

        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(),
                            PackageManager.GET_CONFIGURATIONS);
            versionCode = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        if (versionCode == 0) {
            return;
        }

        // 访问网络的方法
        HashMap hashMap = new HashMap();
        hashMap.put("version_code", versionCode);
//        hashMap.put("version_code", 0);  // 测试更新接口使用
        Connection.getInstance().post(CheckUpdateResponse.class, MyUrl.CHECK_UPDATE, hashMap, new Connection.ResponseListener() {
            @Override
            public void tryReturn(int id, Object response) {
                switch (id) {
                    case 200:
                        CheckUpdateResponse data = (CheckUpdateResponse) response;
                        showUpdateDialog(context,
                                data.getData().getVersion(),
                                data.getData().getContent(),
                                data.getData().getApk_url(),
                                data.getData().getPage_url());
                        break;
                    case -2:
                        if (showToast) {
                            ToastUtil.showLong(context,"可能网络不太好，可直接访问http://moxing.guo.zone下载");
                        }
                        break;
                    default:
                        if (showToast) {
                            ToastUtil.showShort(context,((HttpResponse) response).getMsg());
                        }
                        break;
                }
            }
        });
    }

    public static void showUpdateDialog(final Context context, final String versionName, final String content, final String apkUrl, final String pageUrl) {
        final AlertDialog updateDialog = new AlertDialog.Builder(context, AlertDialog.THEME_HOLO_LIGHT).create();
        updateDialog.show();
        View viewUpdate = LayoutInflater.from(context).inflate(R.layout.dialog_check_update, null);
        Window dialogWindow = updateDialog.getWindow();
        WindowManager.LayoutParams wlp = dialogWindow.getAttributes();
        dialogWindow.setAttributes(wlp);
        updateDialog.setContentView(viewUpdate);

        TextView tvVersion = (TextView) viewUpdate.findViewById(R.id.tv_version);
        TextView tvContent = (TextView) viewUpdate.findViewById(R.id.tv_content);
        TextView tvCancel = (TextView) viewUpdate.findViewById(R.id.tv_cancel);
        TextView tvDownload = (TextView) viewUpdate.findViewById(R.id.tv_download);
        TextView tvInstall = (TextView) viewUpdate.findViewById(R.id.tv_install);

        tvVersion.setText("新版本：V " + versionName);
        tvContent.setText(content);
        tvContent.setMovementMethod(new ScrollingMovementMethod());

        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();
            }
        });
        tvDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse(pageUrl);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                context.startActivity(intent);
            }
        });
        tvInstall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();

                VersionUpdateConfig.getInstance()//获取配置实例
                        .setContext(context)//设置上下文
                        .setDownLoadURL(apkUrl)//设置文件下载链接
                        .setNewVersion(versionName)//设置即将下载的APK的版本号,避免重复下载
                        .setFileSavePath( LocalPath.APP_PATH)//设置文件保存路径（可不设置）
                        .setNotificationIconRes(R.drawable.icon)//设置通知图标
                        .setNotificationSmallIconRes(R.drawable.icon)//设置通知小图标
                        .setNotificationTitle(context.getString(R.string.app_name) + "更新中...")//设置通知标题
                        .startDownLoad();//开始下载
            }
        });

        // 设置点击外面或物理键消失
        updateDialog.setCancelable(true);
    }

}
